# -*- coding: UTF-8 -*-
"""
    @Project ：auto_translate_voice
    @File ：utils.py
    @Author ：lc
    @Date ：2022.4.26 17:55
"""
import os
import time

import openpyxl
import pyautogui
import pywinauto
from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from pywinauto.keyboard import SendKeys
import xlrd

from config import ev_shortcut_key_start, ev_shortcut_key_end, quick_macro_left_trim, quick_macro_right_trim, \
    trim_save_path, record_config_file


def is_exist_element(driver, location):
    """
    判断页面元素是否存在
    :param driver: 驱动对象
    :param location: 对象定位资源
    :return:
    """
    try:
        driver.find_element(*location)
        return True
    except Exception as e:
        return False


def swipe_web(driver):
    """
    滑动页面滚动条
    :param driver: 驱动
    :return: none
    """
    # 获取内嵌div的位置 并设置滚动条移动的值
    # js = "document.getElementById('agreementMain').scrollTop=1000"
    js = 'window.scrollBy(0, 700)'
    # 调用js方法
    driver.execute_script(js)
    print("滑动结束...")


def assert_alert_close(driver, location):
    """
    关闭弹窗
    :param driver: 驱动对象
    :param location: 驱动定位资源
    :return:
    """
    if is_exist_element(driver, location):
        driver.find_element(location[0], location[1] + "//button").click()
        print("点击关闭了...")


def assert_web_open_success(driver, location1, location):
    """
    判断网页打开状态
    :param driver: 驱动
    :param location1: 网页标签
    :param location: 弹窗
    :return: none
    """
    print("等待结束...")
    while 1:
        time.sleep(3)
        if not is_exist_element(driver, location1):
            print("网页打开不正常")
            driver.refresh()
            time.sleep(2)
            assert_alert_close(driver, location)
        else:
            print("网页打开正常")
            break
    if is_exist_element(driver, (By.XPATH, "//*[@class='ms-Modal-scrollableContent scrollableContent-234']")):
        driver.find_element(By.XPATH, "//*[@class='ms-Modal-scrollableContent scrollableContent-234']//span").click()
        print("关闭浏览器提示窗口")


def get_element(location, driver):
    """
    :param location:元素定位信息
    :param driver 驱动对象
    :return:元素对象
    """
    # 显示等待
    return WebDriverWait(driver, 10).until(lambda x: x.find_element(*location))


def input_my_text(text, driver):
    """
    输入翻译文本
    :param text: 输入文本
    :param driver: 驱动
    :return: none
    """
    text_area = driver.find_element(By.XPATH, "//div[@id='acc-rich-text-editor']")
    text_area.click()
    text_area.send_keys(Keys.CONTROL, 'a')
    text_area.send_keys(Keys.BACKSPACE)
    text_area.send_keys(text)
    time.sleep(2)


def record(driver, text, sex, emotion):
    """
    录音
    :param driver: 驱动
    :param text: 配音文本
    :param sex: 声优性别
    :return: none
    """
    # 清除输入文本信息
    input_my_text(text, driver)
    print("清空文本")
    # assert_attention_close(driver)
    # 选第一个声优
    # driver.find_element(By.XPATH, "//div[@class='panel-body']/div[2]/div[2]/div/div/div[2]/div/div/div").click()
    # 选择声优男/女
    select_gender_voice(driver, sex)
    # 选择声优情绪
    select_voice_emotion(driver, emotion)
    print("选完声优")
    # 打开录音
    print("开始录音...")
    pyautogui.hotkey(*ev_shortcut_key_start)
    time.sleep(2)
    # 播放
    driver.find_element(By.XPATH, "//button[@title='播放']").click()
    time.sleep(5)
    # 时长
    try:
        record_time = driver.find_element(By.XPATH, "//span[@class='progress-control-container']/span[2]").text
        print(record_time, type(record_time), record_time[3:])
        if record_time[3:] == '00':
            print("!!!!!获取到时间是00")
            raise Exception
        time.sleep(int(record_time[3:]))
        # 结束录音
    except Exception as e:
        print("出错了...", e)
    finally:
        pyautogui.hotkey(*ev_shortcut_key_end)
        print("结束录音...")


def select_gender_voice(driver, sex):
    """
    选择声优
    :param driver:驱动对象
    :param sex: 男m,女f
    :return:none
    """
    driver.find_element(By.XPATH, "//div[@class='panel-body']/div[2]/div[2]/div/div/div[2]/div/div/button").click()
    time.sleep(1)
    if sex == "man1":
        # guy男性
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[5]/div").click()
        time.sleep(1)
    if sex == "woman1":
        # 女性Aria
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[4]/div").click()
        time.sleep(1)
    if sex == 'woman2':
        # 女性Jenny
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[1]/div").click()
        time.sleep(1)
    if sex == 'woman3':
        # Jenny Multilingual女性
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[2]/div").click()
        time.sleep(1)
    if sex == 'woman4':
        # Sara女性
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[6]/div").click()
        time.sleep(1)
    if sex == 'man2':
        # 男Davis
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[3]/div").click()
        time.sleep(1)
    if sex == 'man3':
        # Tony男
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[7]/div").click()
        time.sleep(1)
    if sex == 'man4':
        # Jason
        driver.find_element(By.XPATH, "//div[@class='ms-List-page']/div[10]/div").click()
        time.sleep(1)
    driver.find_element(By.XPATH, "//span[text()='确认']").click()
    time.sleep(3)
    # assert_attention_close(driver)


def select_voice_emotion(driver, emotion):
    # 打开下来框
    driver.find_element(By.XPATH, "//div[@class='ms-Dropdown-container dropdown']//div/span[2]").click()
    time.sleep(1)
    driver.find_element(By.XPATH, f"//span[@class='voicestyle-dropdown-item-wrapper']/span[text()='{emotion}']").click()
    time.sleep(1)


def sound_record(sound_time):
    """
    录制声音
    :param sound_time: 声音时长
    :return: none
    """
    # 开始录制
    pyautogui.hotkey('Ctrl', 'F1')
    # 呼出主界面
    pyautogui.hotkey('Ctrl', 'F3')
    time.sleep(sound_time)
    # 结束录制
    pyautogui.hotkey('Ctrl', 'F2')


def first_trim(driver, path, file_name):
    """
    选择录音文件
    :param driver: 驱动
    :param path: 音频地址
    :param file_name: 文件名
    :return: none
    """
    # 点击打开文件
    driver.find_element(By.XPATH, "//div[@class='md-file-picker__wrapper']").click()
    app = pywinauto.Desktop()
    # 选中文件上传的窗口
    dlg = app["打开"]
    # 选择文件地址输入框，点击激活
    dlg["Toolbar3"].click()
    # 键盘上输入上传文件的路径
    SendKeys(path)
    # 键盘输入回车，打开该路径
    SendKeys("{VK_RETURN}")
    # 选中文件名输入框，输入文件名
    dlg["文件名(&N):Edit"].type_keys(file_name)
    # 点击打开
    # dlg["打开[&O]"].click()
    SendKeys("{VK_RETURN}")
    time.sleep(3)


def call_quick_macro_left(driver):
    """
    剪辑左边定位
    :param driver: 驱动
    :return: none
    """
    # 定位左侧无声
    SendKeys(quick_macro_left_trim)
    print("已定位左侧无声区")
    time.sleep(1)
    print(driver.find_element(By.XPATH, "//div[@class='progress-line']").location)
    return driver.find_element(By.XPATH, "//div[@class='progress-line']").location
    # return driver.find_element(By.XPATH, "//div[@class='progress-line']").get_attribute('data-value')


def call_quick_macro_right(driver):
    """
    剪辑右边定位
    :param driver: 驱动
    :return: none
    """
    # 定位右侧无声
    SendKeys(quick_macro_right_trim)
    print("已定位右侧无声区")
    time.sleep(5)
    return driver.find_element(By.XPATH, "//div[@class='progress-line']").location
    # return driver.find_element(By.XPATH, "//div[@class='progress-line']").get_attribute('data-value')


def trim(driver, flag):
    """
    剪辑
    :param driver: 驱动
    :param flag: 左右区间
    :return: none
    """
    start, end = None, None
    if flag == "left":
        # 左裁剪条
        left_trim = driver.find_element(By.XPATH, "//div[@class='control-bar cb-left active']")
        # print("左裁剪条：", left_trim.location)
        call_quick_macro_left(driver)
        start = left_trim
        end = driver.find_element(By.XPATH, "//div[@class='progress-line']")
    if flag == 'right':
        right_trim = driver.find_element(By.XPATH, "//div[@class='control-bar cb-right']")
        # print("右裁剪条：", right_trim.location)
        call_quick_macro_right(driver)
        start = right_trim
        end = driver.find_element(By.XPATH, "//div[@class='progress-line']")
    action = ActionChains(driver)
    action.drag_and_drop(start, end)
    action.perform()
    print("拖动滚动条了")


def save_file(driver):
    """
    保存后剪辑音频
    :param driver: 驱动
    :return: none
    """
    # 保存
    driver.find_element(By.XPATH, "//button[@class='el-button btn-cut el-button--default']").click()
    time.sleep(1)
    driver.find_element(By.XPATH, "//*[@class='btn-save']").click()
    time.sleep(1)
    driver.find_element(By.XPATH, "//div[@class='block-download']//a[text()='返回']").click()
    time.sleep(1)
    driver.find_element(By.XPATH, "//button[@class='el-button btn-exit el-button--default']").click()
    time.sleep(1)
    driver.find_element(By.XPATH, "//div[@class='block-cancel-edit']//span").click()
    time.sleep(1)


def get_record_text(file_path, start):
    """
    获取所有配音文本
    :return: none
    """
    wb = xlrd.open_workbook(file_path)
    sheet = wb.sheet_by_index(0)
    text_list = list()
    for row_num in range(start, wb.sheet_by_index(0).nrows):
        row_data = sheet.row_values(row_num)
        text_list.append(row_data)
    print(text_list)
    return text_list


def assert_attention_close(driver):
    """
    判断刷新框并关闭----暂不生效，没有调好
    :param driver:
    :return:
    """
    print("开始判断刷新框...")
    # WebDriverWait(driver, 10).until(lambda x: x.find_element(By.XPATH, "//div[@class='content-242']"))
    # 判断是否刷新
    if is_exist_element(driver, (By.XPATH, "//div[@class='content-242']")):
        driver.find_element(By.XPATH, "//span[text()='刷新']").click()
        print("点击刷新...")
        # 是否刷新后打开正常
        assert_web_open_success(driver, (By.XPATH, r"//img[@alt='Microsoft Azure']"),
                                (By.XPATH, "//*[@id='ModalFocusTrapZone148']"))
        # 下滑
        swipe_web(driver)


def delete_domain_name():
    """
    删除文件名中含的域名
    :return: none
    """
    file_list = os.listdir(trim_save_path)
    for file_name in file_list:
        if r" (mp3cut.net)" in file_name:
            old_name = trim_save_path + os.sep + file_name
            new_name = trim_save_path + os.sep + file_name.replace(r" (mp3cut.net)", "")
            os.rename(old_name, new_name)


def get_all_text():
    """
    获取所有中文需翻译文本
    :return: none
    """
    wb = openpyxl.load_workbook(record_config_file)
    sheet = wb.active
    cells = sheet['B']
    text_list = list()
    for item in cells:
        if item.value != 'content':
            text_list.append(item.value)
    return text_list


def save_all_translate_text(text):
    """
    保存翻译文本信息
    :param text: 翻译后文本列表
    :return: none
    """
    wb = openpyxl.load_workbook(record_config_file)
    sheet = wb.active
    cells = sheet['B']
    print(len(cells))
    for num in range(1, len(cells)):
        # print(num)
        sheet[f'J{num + 1}'].value = cells[num].value
        # print(sheet[f'E{num + 1}'].value, cells[num].value)
        # print(cells[num].value, text[num - 1])
        cells[num].value = text[num - 1]
    wb.save(record_config_file)

# //div[@id='ModalFocusTrapZone4013']
